package bigo.data;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

/**
 *
 * @author songliu
 */
public class RowIndex implements WritableComparable<RowIndex> {

    public int rowIndex;
    public String sourceMatrix;

    public RowIndex() {
    }

    public RowIndex(int rowIndex, String sourceMatrix) {
        this.rowIndex = rowIndex;
        this.sourceMatrix = sourceMatrix;
    }

    @Override
    public void write(DataOutput out) throws IOException {
        out.writeInt(rowIndex);
        out.writeUTF(sourceMatrix);
    }

    @Override
    public void readFields(DataInput in) throws IOException {
        this.rowIndex = in.readInt();
        this.sourceMatrix = in.readUTF();
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 37 * hash + this.rowIndex;
        return hash;
    }

    /**
     * Not used, since it may cause an unknown error which gives me EOF error
     * @param o
     * @return
     */
    public int compareTo(RowIndex o) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Use the raw comparator against Bytes
     */
    public static class Comparator implements RawComparator<RowIndex> {

        public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
            int row1 = WritableComparator.readInt(b1, s1);
            int row2 = WritableComparator.readInt(b2, s2);
            if (row1 - row2 == 0) {
                return WritableComparator.compareBytes(b1, s1 + 4, l1 - 4, b2, s2 + 4, l2 - 4);
            }
            return row1 - row2;
        }

        public int compare(RowIndex o1, RowIndex o2) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }

    public static class GroupComparator implements RawComparator<GroupComparator> {

        public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
            return -(WritableComparator.readInt(b2, s2)
                    - WritableComparator.readInt(b1, s1));
        }

        public int compare(GroupComparator o1, GroupComparator o2) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}
